package com.fenqing.leetcode.code.interview;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.fenqing.annotations.Execute;
import com.fenqing.core.Topic;
import com.fenqing.utils.IntTwoArrayToStringEncoder;

import java.util.stream.Collectors;

public class Topic0107 extends Topic {

    /**
     * 构造器
     *
     * @param input     输入
     */
    public Topic0107(String input) {
        super(input);
    }


    @Execute(isVoid = true, voidReturnIndex = 0, voidReturnEncoder = IntTwoArrayToStringEncoder.class)
    public void rotate(int[][] matrix) {
        final int len = matrix.length,
                last = len - 1,
                height = len / 2;
        for (int i = 0; i < height; i++) {
            // 循环层数
            //循环每一层的一半
            int lastI = last - i;
            for (int j = i; j < lastI; j++) {

                int lastJ = last - j;
                // 取出第一个元素
                int temp = matrix[i][j];
                // 将第一个元素放到最后一个位置
                matrix[i][j] = matrix[lastJ][i];
                matrix[lastJ][i] = matrix[lastI][lastJ];
                matrix[lastI][lastJ] = matrix[j][lastI];
                matrix[j][lastI] = temp;
            }
        }
    }

    public static void main(String[] args) {
        String input = "[[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]";
        Topic0107 topic = new Topic0107(input);
        String output = topic.run();
        System.out.println("input: \n" + print(input));
        System.out.println("output: \n" + print(output));
    }

    public static String print(String matrix) {
        JSONArray objects = JSONUtil.parseArray(matrix);
        String sb = "[\n" +
                objects.stream().map(JSONUtil::toJsonStr).collect(Collectors.joining(",\n")) +
                "\n]";
        return sb;
    }
}
